//
//  WDLoanDetailController.m
//  Zhihuijinfu
//
//  Created by 王笛 on 2017/1/20.
//  Copyright © 2017年 王笛. All rights reserved.
//

#import "WDLoanDetailController.h"
#import "WDLoanDetailHeadView.h"
#import "WDLoandetailCell.h"
#import "WDLoan.h"
#import "WDPromptBox.h"
#import "WDDataInformation.h"
#import "WDMaterialDetail.h"
#import "WDData.h"
#import "WDOriImageController.h"
#import "WDEditLoanController.h"
#import "WDCheckController.h"

@interface WDLoanDetailController () <UITableViewDelegate, UITableViewDataSource, WDloanDetailCellDelegate>
/** tableView */
@property (nonatomic, strong) UITableView *tabelView;
/** 资料数据 */
@property (nonatomic, strong) NSArray *dataArray;
/** 图片数据 */
@property (strong, nonatomic) NSArray *images;

@end

@implementation WDLoanDetailController

- (void)loadTabelView
{
    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WDScreenW, WDScreenH - 30) style:UITableViewStyleGrouped];
    
    //添加这句话，tableView就不会被遮盖
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    tableView.dataSource = self;
    tableView.delegate = self;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tabelView = tableView;
    
    WDLoanDetailHeadView *headView = [WDLoanDetailHeadView loanDetailHeadView];
    headView.loan = self.loan;
    CGRect newFrame = CGRectMake(0, 0, WDScreenW, self.loan.detailHeadH);
    
    headView.frame = newFrame;
    
    [self.tabelView setTableHeaderView:headView];
    
    if (self.isHiddenBtn) {
        tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
    } else {
        tableView.contentInset = UIEdgeInsetsMake(0, 0, 50, 0);
    }
    
    [self.view addSubview:self.tabelView];
}

- (void)loadButtomBtn
{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    
    if (self.isHiddenBtn) {
        btn.hidden = YES;
    } else {
        btn.hidden = NO;
    }
    
    [btn setBackgroundImage:[UIImage imageWithColor:[UIColor colorWithWhite:1 alpha:1]] forState:UIControlStateNormal];
    [btn setBackgroundImage:[UIImage imageWithColor:[UIColor colorWithWhite:0.9 alpha:1]] forState:UIControlStateHighlighted];
    
    [btn setTitle:@" 编辑进件" forState:UIControlStateNormal];
    [btn setTitleColor:ColorForRGB(0x4A90E2) forState:UIControlStateNormal];
    btn.titleLabel.font = [UIFont systemFontOfSize:15];
    [btn setImage:[UIImage imageNamed:@"icon-编辑"] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(editMaterial) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:btn];
    
    [btn makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(0);
        make.height.equalTo(54);
    }];
    
    //加阴影效果
    
    btn.layer.shadowOffset = CGSizeMake(1, 1);
    
    btn.layer.shadowOpacity = 0.8;
    
    btn.layer.shadowColor = [UIColor blackColor].CGColor;
    
}

- (void)editMaterial
{
    //进入编辑页面
    WDEditLoanController *tempVC = [[WDEditLoanController alloc] init];
    
    tempVC.loan = self.loan;
    
    tempVC.view.backgroundColor = WDBackColor;
    
    [self.navigationController pushViewController:tempVC animated:YES];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    if (self.isCheck) {
        [self loadNavItemWithAction:@selector(clickBackBtn) btnImage:@"icon_back" btnSelImage:@"icon_back" title:@"贷款详情"];
    } else {
    
        [self loadNavItemWithLeftAction:@selector(clickBackBtn) leftBtnImage:@"icon_back" leftBtnSelImage:@"icon_back" title:@"贷款详情" rihgtAction:@selector(clickDetailBtn) rightBtnImage:@"icon-operation_his" rightBtnSelImage:@"icon-operation_his"];
    }
    
    [self loadTabelView];
    
    [self loadButtomBtn];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self sendRequestFileList];
    
    [self.tabelView reloadData];
    
    self.navigationController.navigationBar.hidden = NO;
}

- (void)clickBackBtn
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)clickDetailBtn
{
    //查看详情
    WDCheckController *tempVC = [[WDCheckController alloc] init];
    tempVC.loan = self.loan;
    tempVC.isNotify = NO;
    tempVC.financeID = self.loan.id;
    tempVC.view.backgroundColor = WDBackColor;
    [self.navigationController pushViewController:tempVC animated:YES];
}

/** 金融资料列表信息 */
- (void)sendRequestFileList
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    
    manager.requestSerializer.timeoutInterval = 10.0f;
    
    NSData *cookiesdata = [[NSUserDefaults standardUserDefaults] objectForKey:WDURLLogin];
    if([cookiesdata length]) {
        NSArray *cookies = [NSKeyedUnarchiver unarchiveObjectWithData:cookiesdata];
        NSHTTPCookie *cookie;
        for (cookie in cookies) {
            [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
        }
    }
    
        
    NSDictionary *parameters = @{
                                 @"finance_id":self.loan.id,
                                 @"material_type":@1,
                                 @"ctype":@3
                                 };
    NSString *url = [NSString stringWithFormat:@"%@%@", WDURLPrefix, WDURLFinanceFileList];
    
    [manager POST:url parameters:parameters constructingBodyWithBlock:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        WDDataInformation *dataInformation = [WDDataInformation mj_objectWithKeyValues:responseObject];
        
        self.dataArray = [WDMaterialDetail mj_objectArrayWithKeyValuesArray:dataInformation.material_list];
        
        self.images = [WDData mj_objectArrayWithKeyValuesArray:dataInformation.data];
        
        NSMutableSet *tempSet = [NSMutableSet set];
        NSMutableArray *tempArr = [NSMutableArray array];
        WDMaterialDetail *materialDetail;
        WDData *materData;
        
        for (materData in _images) {
            [tempSet addObject:materData.file_type];
        }
        NSMutableArray *materArr = [NSMutableArray array];
        for (NSString *tempStr in tempSet) {
            [materArr addObject:tempStr];
        }
        
        for (materialDetail in self.dataArray) {
            for (int i = 0; i < materArr.count; i++) {
                if ([materialDetail.id isEqualToString:materArr[i]]) {
                    [tempArr addObject:materialDetail];
                }
            }
        }
        self.dataArray = tempArr;
        
        [self.tabelView reloadData];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //WDLog(@"%@", error);
        
    }];
}

#pragma mark - tableView代理
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    WDLoandetailCell *cell = [WDLoandetailCell loanDetailCellWithTableView:tableView];
    cell.delegate = self;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (indexPath.row == 0 && indexPath.row != (self.dataArray.count - 1)) {
        cell.firstCell = YES;
        cell.lastCell = NO;
    } else if (indexPath.row == (self.dataArray.count - 1) && indexPath.row != 0) {
        cell.lastCell = YES;
        cell.firstCell = NO;
    } else if (indexPath.row != 0 && indexPath.row != self.dataArray.count - 1){
        cell.firstCell = NO;
        cell.lastCell = NO;
    } else {
        cell.firstCell = YES;
        cell.lastCell = YES;
    }
    
    
    
    NSMutableArray *images = [NSMutableArray array];
    
    WDData *materData;
    cell.materialDetail = self.dataArray[indexPath.row];
    
    for (materData in self.images) {
        
        if ([materData.file_type isEqualToString:cell.materialDetail.id]) {
            [images addObject:materData];
        }
    }
    
    cell.materialDetail.DetailCellH = ((images.count + 1) / 2) * 102;
    
    cell.imagesData = images;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    WDMaterialDetail *materialDetail = self.dataArray[indexPath.row];
    return materialDetail.DetailCellH + 45;
}

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 200;
}

#pragma mark - WDLoanDetailCellDelegete
- (void)loanDetailShowOriginalImage:(NSArray *)images clickIndex:(NSInteger)index
{
    WDOriImageController *tempVC = [[WDOriImageController alloc] init];
    
    tempVC.images = images;
    tempVC.index = index;
    [self.navigationController pushViewController:tempVC animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
